# -*- coding: utf-8 -*- 

#########################################################################
## This is a samples controller
## - index is the default action of any application
## - user is required for authentication and authorization
## - download is for downloading files uploaded in the db (does streaming)
## - call exposes all registered services (none by default)
#########################################################################
import urllib
import urllib2 

if 0:
    from gluon.globals import *
    from gluon.html import *
    from gluon.http import *
    from gluon.sqlhtml import SQLFORM, SQLTABLE, form_factory
    session = Session()
    request = Request()
    response = Response()  

@auth.requires_login()
def index():
                
    response.subtitle=BR()
        
    return dict(projects=projects_all, languages=languages_all)

@auth.requires_login()
def lang_and_prj():
    
    lang_id=request.args[0]
    
    prj_and_lang=db((db.language.id==db.project_language.language) & (db.project.id==db.project_language.project))    
    projects = prj_and_lang(db.language.code== lang_id).select(orderby=2)
    
    language=db(db.language.code == lang_id).select().first()
    
    response.subtitle=language.description
        
    return dict(projects=projects, language=language)

@auth.requires_login()
def prj_and_lang():
    
    prj_id=request.args[0]
    
    prj_and_lang=db((db.language.id==db.project_language.language) & (db.project.id==db.project_language.project))    
    languages = prj_and_lang(db.project.code== prj_id).select(orderby=2)
    
    project=db(db.project.code == prj_id).select().first()
    
    response.subtitle=project.description
        
    return dict(languages=languages, project=project)

def _updated_statistic(id):
    
    tot_item = db(db.item.project_language==id).count()
    tot_tran= db((db.item.project_language==id) & (db.item.target != '') & (db.item.target != None)).count()
          
    #Update record
    db(db.project_language.id ==id).update(tot_item = tot_item, tra_item=tot_tran)

@auth.requires_login()
def items():
    
    prj_code=request.args[0]
    lang_code=request.args[1]
          
    prj_and_lang=db((db.language.id==db.project_language.language) & (db.project.id==db.project_language.project))
    
    prj = prj_and_lang((db.language.code== lang_code) & 
                             (db.project.code== prj_code)).select().first()
    
    src_lang=db((db.project.code==prj_code) &
                (db.language.id==db.project.source_language)).select().first()
                                     
    record = db.item(request.vars.id)
    
    if record:
        form=SQLFORM(db.item, record)
    else:
        form=SQLFORM(db.item)
    
    if form.accepts(request.vars, formname='form_item'):
        response.flash=T('Item saved.')
        _updated_statistic(_prj.project_language.id)
    elif form.errors:
        response.flash=T('Error saving item.')

    response.subtitle="%s -> %s" %(prj.project_language.project.description, prj.project_language.language.description)
                    
    return dict(project_language=prj.project_language.id, 
                form=form, 
                prj_code=prj_code, 
                lang_code=lang_code,
                src_lang=src_lang.language.code)

@auth.requires_login()
def list_items():
    
    prj_code=request.args[0]
    lang_code=request.args[1]
    prj_and_lang=db((db.language.id==db.project_language.language) & (db.project.id==db.project_language.project))
    
    _projects = prj_and_lang((db.language.code== lang_code) & (db.project.code== prj_code) ).select().first()
    
    items=db(db.item.project_language == _projects.project_language.id).select()
    
    return _build_table(items, prj_code, lang_code)
    

def _build_table(items, prj_code, lang_code):
    
    ret=''
    
    _project=db((db.project.code==prj_code) & (db.language.id == db.project.source_language)).select().first()
    
    for i, item in enumerate(items):
        ret+= TR(
                 TD(item.key ),
                 TD(item.source, _lang='%s' %_project.language.description),
                 TD(
                        item.target, _lang='%s' %lang_code
                    ),
                 TD(
                    A(
                      IMG(_src=URL( request.application , 'static/images', 'application_edit.png')), _href='#', 
                      _onclick="$.ajax({type:'GET', url:'%s', data:'id=%s', dataType:'json' , success:set_field_callback})" %(URL(request.application, 'default','get_item.json'), item.id))),
                 TD(
                    A(
                    IMG(_src=URL( request.application , 'static/images', 'cancel.png')), _href='#', _onclick='delete_key(\'%s\',\'%s\',%s)' %(prj_code, lang_code ,item.id))),
                    _class='even' if not i%2 else 'odd'
                 ).xml()
                                         
    return ret
    

@auth.requires_login()
def search_items():
    
    key=request.vars.search
    prj_code=request.vars.prj_code
    lang_code=request.vars.lang_code
    
    prj_and_lang=db((db.language.id==db.project_language.language) & (db.project.id==db.project_language.project))
    
    _projects = prj_and_lang((db.language.code== lang_code) & (db.project.code== prj_code) ).select().first()
    
    items=db((db.item.project_language == _projects.project_language.id) & 
             ((db.item.source.like('%' + key + '%')) | 
             (db.item.target.like('%' + key + '%')) |
             (db.item.key.like('%' + key + '%')))).select()
    
    return _build_table(items, prj_code, lang_code)    
    

@auth.requires_login()
def get_item():
        
    item_id=request.vars.id
    
    _item=db(db.item.id==item_id).select().first()
    
    _ret=dict(id=_item.id  ,key=_item.key, source= _item.source, target=_item.target, comment=_item.comment, suggestion= _item.suggestion, project_language=_item.project_language)
        
    return _ret

@auth.requires_login()
def delete_item():
    
    prj_code=request.args[0] 
    lang_code=request.args[1]
    item_id=request.args[2] 
       
    crud.delete(db.item, item_id, URL('items', args=[prj_code, lang_code]))
    
def suggest():
    
    src_lang=request.vars.src_lang
    lang_code=request.vars.lang_code
    source=request.vars.source
    
    # call google calendar API
    
    url= google_translate_api_url %(google_translate_api_key, urllib.quote_plus(source), src_lang ,lang_code)
    
    response = urllib2.urlopen(url)
    html = response.read()
            
    return html    
        
            
def user():
    """
    exposes:
    http://..../[app]/default/user/login 
    http://..../[app]/default/user/logout
    http://..../[app]/default/user/register
    http://..../[app]/default/user/profile
    http://..../[app]/default/user/retrieve_password
    http://..../[app]/default/user/change_password
    use @auth.requires_login()
        @auth.requires_membership('group name')
        @auth.requires_permission('read','table name',record_id)
    to decorate functions that need access control
    """
    
    response.subtitle=''
    
    return dict(form=auth())


def download():
    """
    allows downloading of uploaded files
    http://..../[app]/default/download/[filename]
    """
    return response.download(request,db)


def call():
    """
    exposes services. for example:
    http://..../[app]/default/call/jsonrpc
    decorate with @services.jsonrpc the functions to expose
    supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
    """
    session.forget()
    return service()
